<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: Core.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_Plugin_Core {
	public function onStatistics($event) {
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$select = new Zend_Db_Select ( $table->getAdapter () );
		$select->from ( $table->info ( 'name' ), 'COUNT(*) AS count' )->where ( 'approved = ?', 1 );
		
		$event->addResponse ( $select->query ()->fetchColumn ( 0 ), 'voting' );
	}
	
	public function onUserDeleteBefore($event) {
		$payload = $event->getPayload ();
		if ($payload instanceof User_Model_User) {
			// Delete blogs
			$table = Engine_Api::_ ()->getDbtable ( 'challenges', 'vote' );
			$select = $table->select ()->where ( 'user_id = ?', $payload->getIdentity () );
			$items = $table->fetchAll ( $select );
			foreach ( $items as $item ) {
				$item->delete ();
			}
			
			$table = Engine_Api::_ ()->getDbtable ( 'participants', 'vote' );
			$select = $table->select ()->where ( 'user_id = ?', $payload->getIdentity () );
			$items = $table->fetchAll ( $select );
			foreach ( $items as $item ) {
				$item->delete ();
			}
		}
	}
	
	public function onRenderLayoutDefault($event) {
		$view = $event->getPayload ();
		if ($view instanceof Zend_View) {
			$view->headScript ()->appendFile ( 'application/modules/Vote/externals/scripts/core.js' );
		}
	}
}